import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Upload } from "./entities/upload.entity";
import { CreateUploadDto } from "./dto/create-upload.dto";
import * as fs from "fs";
import * as path from "path";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class UploadService {
	constructor(
		@InjectRepository(Upload)
		private uploadRepository: Repository<Upload>,
		private configService: ConfigService
	) {}

	async create(file: any, type: string = "image"): Promise<Upload> {
		const baseUrl =
			this.configService.get("app.baseUrl") || "http://localhost:3000";

		// 创建上传记录
		const createUploadDto: CreateUploadDto = {
			originalName: file.originalname,
			filename: file.filename,
			mimetype: file.mimetype,
			size: file.size,
			path: file.path,
			url: `${baseUrl}/uploads/${file.filename}`,
			type: type,
		};

		const upload = this.uploadRepository.create(createUploadDto);
		return this.uploadRepository.save(upload);
	}

	async findOne(id: number): Promise<Upload> {
		return this.uploadRepository.findOne({ where: { id } });
	}

	async findAll(): Promise<Upload[]> {
		return this.uploadRepository.find({
			order: { createdAt: "DESC" },
		});
	}

	async remove(id: number): Promise<void> {
		const upload = await this.findOne(id);
		if (upload) {
			// 删除文件
			try {
				fs.unlinkSync(upload.path);
			} catch (error) {
				console.error("文件删除失败", error);
			}
			await this.uploadRepository.remove(upload);
		}
	}
}
